package com.ishare.common.service.base.impl;

import com.ishare.common.constant.RedisKey;
import com.ishare.common.service.base.EmailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

/**
 * @author 李嘉宾
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String mailUserName;


    @Override
    public void saveEmailCodeCache(String email, String cacheCode) {
        //保存到缓存中
        stringRedisTemplate.opsForValue().set(RedisKey.EMAIL_CACHE_CODE.addSuffix(email), cacheCode, 3, TimeUnit.MINUTES);
    }

    @Override
    public void clearEmailCodeFromCache(String email) {
        stringRedisTemplate.delete(RedisKey.EMAIL_CACHE_CODE.addSuffix(email));
    }

    @Override
    public Long getEmailCodeTimeOutValue(String email) {
        return stringRedisTemplate.getExpire(RedisKey.EMAIL_CACHE_CODE.addSuffix(email));
    }

    @Override
    public String getEmailCodeFromCache(String email) {
        //从缓存拿
        return stringRedisTemplate.opsForValue().get(RedisKey.EMAIL_CACHE_CODE.addSuffix(email));
    }

    @Override
    public boolean sendEmailCode(String email, String cacheCode) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(mailUserName);
            mailMessage.setTo(email);
            mailMessage.setSubject("【iShare】邮箱注册验证码");
            mailMessage.setText("【iShare】邮箱注册验证码："+cacheCode+"，请勿把验证码泄露给其他人！3分钟内有效。");
            javaMailSender.send(mailMessage);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
